#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
using namespace std;

class Solution {
public:
    const int INF = 0x3f3f3f3f;
    int numSquares(int n) {
        int t = sqrt(n);
        vector<int> dp(n + 1, INF);
        dp[0] = 0;

        for (int i = 1; i <= t; ++i)
            for (int j = i * i; j <= n; ++j)
                dp[j] = min(dp[j], dp[j - i * i] + 1);

        return dp[n] == INF ? -1 : dp[n];
    }
};